package com.maben.servlet;


import com.alibaba.fastjson.JSON;
import com.maben.pojo.User;
import com.maben.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserSimpleServlet extends HttpServlet {


    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        UserService userService = (UserService) context.getBean("userService");
        final String id = req.getParameter("id");
        if (StringUtils.isBlank(id)) {
            return;
        }
        User user = null;
        try {
            user = userService.queryUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
            user = new User();
        }
        final ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.print(JSON.toJSONString(user));
        outputStream.flush();
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
